<template>
  <div class="container">
    <!-- 分类选择 -->
    <div class="form-section">
      <div class="form-item">
        <span class="label">课程大类：</span>
        <select v-model="form.category" @change="onCategoryChange">
          <option value="">请选择</option>
          <option v-for="(item, index) in categoryList" :key="index" :value="index">
            {{ item }}
          </option>
        </select>
      </div>
      
      <div class="form-item">
        <span class="label">课程：</span>
        <select v-model="form.course" @change="onCourseChange">
          <option value="">请选择</option>
          <option v-for="(item, index) in courseList" :key="index" :value="index">
            {{ item }}
          </option>
        </select>
      </div>
      
      <div class="form-item">
        <span class="label">章节：</span>
        <select v-model="form.chapter" @change="onChapterChange">
          <option value="">请选择</option>
          <option v-for="(item, index) in chapterList" :key="index" :value="index">
            {{ item }}
          </option>
        </select>
      </div>
      
      <div class="form-item">
        <input type="file" accept="video/*" @change="handleFileChange" class="upload-btn" />
      </div>
      
      <div class="form-item" v-if="form.files.length">
        <span>已选视频：</span>
        <div v-for="(file, idx) in form.files" :key="idx" class="file-name">
          {{ file.name || getFileNameFromPath(file.path) }}
        </div>
      </div>
      
      <div class="form-item">
        <button 
          class="upload-btn" 
          :disabled="!canSubmit" 
          @click="uploadVideos"
        >
          上传视频
        </button>
      </div>
    </div>

    <!-- 已上传视频列表 -->
    <div class="table-section" v-if="uploadedVideos.length">
      <div class="video-row" v-for="(item, idx) in uploadedVideos" :key="idx">
        <input 
          type="checkbox" 
          :value="item.fileName" 
          :checked="selectedVideos.includes(item.fileName)" 
          @change="onCheckboxChange(item.fileName)"
        />
        <span class="file-name">{{ item.fileName }}</span>
        <button class="play-btn" @click="preview(item.url)">播放</button>
        <button class="delete-btn" @click="deleteSingle(item.fileName)">删除</button>
      </div>
      
      <button 
        class="delete-btn" 
        :disabled="!selectedVideos.length" 
        @click="deleteSelected"
        style="margin-top: 0.5rem;"
      >
        批量删除
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import axios from 'axios'; // 需要安装 axios: npm install axios

const BACKEND_BASE_URL = 'http://172.172.9.110:8010'; // 后端地址

const form = ref({
  category: '',
  course: '',
  chapter: '',
  files: [] // 存储选中的文件对象
});

const categoryList = ['人工智能', '机器学习'];
const courseList = ['Java', 'Python'];
const chapterList = ['第一章', '第二章'];

const uploadedVideos = ref([]);
const selectedVideos = ref([]);

const canSubmit = computed(() => 
  form.value.category !== '' &&
  form.value.course !== '' &&
  form.value.chapter !== '' &&
  form.value.files.length > 0
);

// 选择文件处理
function handleFileChange(e) {
  form.value.files = Array.from(e.target.files);
}

// 辅助函数：从路径中获取文件名
function getFileNameFromPath(path) {
  return path ? path.split('/').pop() : '未知视频';
}

// 上传视频
async function uploadVideos() {
  if (!canSubmit.value) {
    alert('请填写完整信息并选择视频');
    return;
  }

  const formData = new FormData();
  const file = form.value.files[0]; // 假设单文件上传

  formData.append('file', file);
  formData.append('category', categoryList[form.value.category]);
  formData.append('course', courseList[form.value.course]);
  formData.append('chapter', chapterList[form.value.chapter]);

  try {
    const response = await axios.post(
      `${BACKEND_BASE_URL}/api/video/upload`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    );

    if (response.status === 200) {
      uploadedVideos.value.push({
        fileName: response.data.fileName,
        url: response.data.url
      });
      form.value.files = []; // 清空已选文件
      alert('上传成功');
    } else {
      alert(`上传失败: ${response.data.message}`);
    }
  } catch (error) {
    console.error('上传失败:', error);
    alert('上传请求失败，请重试');
  }
}

// 单个删除
async function deleteSingle(fileName) {
  if (!confirm('确定删除该视频吗？')) return;

  try {
    await axios.delete(
      `${BACKEND_BASE_URL}/api/video/${encodeURIComponent(fileName)}`
    );

    uploadedVideos.value = uploadedVideos.value.filter(v => v.fileName !== fileName);
    selectedVideos.value = selectedVideos.value.filter(f => f !== fileName);
    alert('删除成功');
  } catch (error) {
    console.error('删除失败:', error);
    alert('删除请求失败，请重试');
  }
}

// 批量删除
async function deleteSelected() {
  if (selectedVideos.value.length === 0) {
    alert('请选择要删除的视频');
    return;
  }

  if (!confirm(`确定批量删除 ${selectedVideos.value.length} 个视频吗？`)) return;

  try {
    await axios.post(
      `${BACKEND_BASE_URL}/api/video/deleteBatch`,
      { fileNames: selectedVideos.value },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    uploadedVideos.value = uploadedVideos.value.filter(
      v => !selectedVideos.value.includes(v.fileName)
    );
    selectedVideos.value = [];
    alert('批量删除成功');
  } catch (error) {
    console.error('批量删除失败:', error);
    alert('批量删除请求失败，请重试');
  }
}

// 多选处理
function onCheckboxChange(fileName) {
  if (selectedVideos.value.includes(fileName)) {
    selectedVideos.value = selectedVideos.value.filter(f => f !== fileName);
  } else {
    selectedVideos.value.push(fileName);
  }
}

// 播放视频
function preview(url) {
  window.open(url, '_blank'); // 浏览器中直接打开视频链接
}
</script>

<style scoped>
/* 样式保持一致，仅调整 UniApp 单位 */
.container {
  padding: 1.5rem;
  background: #f7f7f7;
  min-height: 100vh;
}

.form-section {
  background: #fff;
  border-radius: 0.75rem;
  margin-bottom: 1.5rem;
  padding: 1.5rem;
}

.form-item {
  margin-bottom: 1.25rem;
  display: flex;
  align-items: center;
}

.label {
  width: 7.5rem;
  font-weight: bold;
  flex-shrink: 0;
}

select {
  flex: 1;
  padding: 0.75rem;
  border: 1px solid #eee;
  border-radius: 0.5rem;
  background: #f5f7fa;
  box-sizing: border-box;
}

.file-name {
  flex: 1;
  margin-left: 1rem;
  font-size: 0.875rem;
  color: #333;
  word-break: break-all;
}

.upload-btn, .delete-btn, .play-btn {
  margin-left: 1rem;
  padding: 0.75rem 2rem;
  border: none;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  flex-shrink: 0;
}

.play-btn {
  background: #67C23A;
}

.delete-btn {
  background: #F56C6C;
}

.upload-btn {
  background: #409EFF;
}

.upload-btn:disabled, .delete-btn:disabled, .play-btn:disabled {
  background: #bbb;
  color: #fff;
}

.table-section {
  background: #fff;
  border-radius: 0.75rem;
  padding: 1.5rem;
}

.video-row {
  display: flex;
  align-items: center;
  margin-bottom: 1rem;
  border-bottom: 1px solid #eee;
  padding-bottom: 1rem;
}

.video-row:last-child {
  border-bottom: none;
}

video-row input[type="checkbox"] {
  margin-right: 1rem;
}

video-row button {
  margin-left: 0.5rem;
}
</style>